package test

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"net/http"
	"testing"
	"time"

	"jiance_server/config"
	"jiance_server/log"

	"github.com/cdongyang/library/web/handler/base"
)

var startChan = make(chan struct{})

func init() {
	go func() {
		for range time.Tick(time.Millisecond * 1) {
			req, err := http.NewRequest("POST", "http://"+config.GetConfig().Socket+"/login", nil)
			if err != nil {
				log.Panicln(err)
			}
			_, pattern := http.DefaultServeMux.Handler(req)
			if pattern == "/login" {
				break
			}
		}
		log.Debugln("listen ", config.GetConfig().Socket)
		close(startChan)
		err := http.ListenAndServe(config.GetConfig().Socket, nil)
		log.Debugln(err)
	}()
}

type Example struct {
	Request       interface{}
	Response      base.Result
	URL           string
	ExpectSuccess bool
}

// Request and Response are json
func RunJSONExamples(t *testing.T, examples []Example) {
	for i := range examples {
		RunJSONExample(t, &examples[i])
	}
}

func RunJSONExample(t *testing.T, example *Example) {
	<-startChan
	reqbs, err := json.Marshal(example.Request)
	if err != nil {
		t.Error(err)
		return
	}
	resp, err := http.Post("http://"+config.GetConfig().Socket+example.URL, "application/json", bytes.NewReader(reqbs))
	if err != nil {
		t.Error(err)
		return
	}
	respbs, err := ioutil.ReadAll(resp.Body)
	resp.Body.Close()
	if err != nil {
		t.Error(err)
		return
	}
	err = json.Unmarshal(respbs, &example.Response)
	if err != nil {
		t.Error(err)
		return
	}
	if example.ExpectSuccess != example.Response.Success {
		t.Error("result not expect")
	}
}
